Page({
  data: {
    wordList: [], // 当前unit的单词数组
    currentTab: 0, // 当前tab下标
    currentWord: {}, // 当前单词对象
    spellParts: [], // 单词分色拼写
    pronunciationMode: 'us', // 'us'美音 'uk'英音
    phoneticMode: 'split', // 'split'音节拆分 'natural'自然拼读
    moduleTabList: ['学','读','练','拼','默'],
    currentModuleTab: 0,
    playingIndex: -1, // 当前播放音频的tab下标，-1表示无播放
    tabsScrollLeft: 0, // tabs滚动条位置
    spellStage: 1, // 当前拼写轮次 1或2
    spellParts1: [], // 第一轮分组
    spellParts2: [], // 第二轮分组
    spellInput: [], // 用户已选分组
    spellAnswer: [], // 当前轮正确顺序
    spellStatus: '', // '', 'success', 'error'
    spellUniqueParts1: [], // Unique parts of the first group
    spellUniqueParts2: [], // Unique parts of the second group
    playingSpell: false, // 拼写区播放状态
    keyboardRows: [
      [
        { key: 'q', label: 'Q' }, { key: 'w', label: 'W' }, { key: 'e', label: 'E' }, { key: 'r', label: 'R' }, { key: 't', label: 'T' },
        { key: 'y', label: 'Y' }, { key: 'u', label: 'U' }, { key: 'i', label: 'I' }, { key: 'o', label: 'O' }, { key: 'p', label: 'P' }
      ],
      [
        { key: 'a', label: 'A' }, { key: 's', label: 'S' }, { key: 'd', label: 'D' }, { key: 'f', label: 'F' }, { key: 'g', label: 'G' },
        { key: 'h', label: 'H' }, { key: 'j', label: 'J' }, { key: 'k', label: 'K' }, { key: 'l', label: 'L' }
      ],
      [
        { key: 'z', label: 'Z' }, { key: 'x', label: 'X' }, { key: 'c', label: 'C' }, { key: 'v', label: 'V' }, { key: 'b', label: 'B' },
        { key: 'n', label: 'N' }, { key: 'm', label: 'M' }
      ]
    ],
    keyboardVisible: false,
    spellInputStr: '',
    inputFocus: false,
  },

  onLoad(options) {
    const eventChannel = this.getOpenerEventChannel && this.getOpenerEventChannel()
    if (eventChannel && typeof eventChannel.on === 'function') {
      eventChannel.on('acceptUnitWords', (data) => {
        const idx = typeof data.activeIndex === 'number' ? data.activeIndex === -1 ? 0 : data.activeIndex : 0;
        this.setData({
          wordList: data.wordList || [],
          currentTab: idx
        })
        this.updateCurrentWord(idx)
      })
    } else {
      // 兼容直接打开页面时的调试
      this.setData({
        wordList: [], // 或可填充mock数据
        currentTab: 0
      })
    }
  },

  onTabChange(e) {
    const idx = Number(e.detail.value)
    this.setData({ currentTab: idx, currentModuleTab: 0 })
    this.updateCurrentWord(idx)
  },

  onTabChangeCustom(e) {
    const idx = Number(e.currentTarget.dataset.index)
    this.setData({ 
      currentTab: idx, 
      currentModuleTab: 0 
    }, () => {
      this.updateCurrentWord(idx)
      this.scrollTabToCenter(idx)
    })
  },

  updateCurrentWord(idx) {
    const word = this.data.wordList[idx] || {}
    // 处理音标、释义、音节、例句等
    // mean: "n. 意义；意思；含义；重要性；重大；v. 表示…的意思；意思是；意指"
    const mean = word.mean || '';
    const meanArr = mean.split('；');
    const posMap = {};
    meanArr.forEach(item => {
      const match = item.match(/^([a-zA-Z\.]+)\s*(.*)$/);
      if (match) {
        const pos = match[1];
        const cn = match[2];
        if (!posMap[pos]) posMap[pos] = [];
        if (cn) posMap[pos].push(cn);
      }
    });
    const meanList = Object.keys(posMap).map(pos => `${pos} ${posMap[pos].join('；')}`);
    const phonetic = this.data.pronunciationMode === 'us' ? (word.phonetic?.us || '') : (word.phonetic?.uk || '')
    // 简单模拟分色拼写
    const spellParts = word.word ? [word.word[0], word.word.slice(1)] : []
    // 例句
    let exampleEn = '', exampleZh = ''
    let exampleSentences = []
    if (word.sentences && word.sentences.length) {
      exampleEn = word.sentences[0].sContent || ''
      exampleZh = word.sentences[0].tContent || ''
      // 新增：处理所有例句
      exampleSentences = word.sentences.map(sen => ({
        enParts: this.highlightExampleEn(sen.sContent || '', word.word),
        zh: sen.sCn || ''
      }))
    }
    this.setData({
      currentWord: {
        ...word,
        meanList,
        phonetic,
        syllables: word.syllables || [],
        exampleEn,
        exampleZh,
        exampleSentences
      },
      spellParts,
      exampleEnParts: this.highlightExampleEn(exampleEn, word.word),
      currentTab: idx
    }, () => {
      this.scrollTabToCenter(idx)
    })
  },

  onPlaySound() {
    const idx = this.data.currentTab
    const word = this.data.wordList[idx]
    let audioKey = ''
    let type = 2
    if (this.data.pronunciationMode === 'us') {
      audioKey = word.usspeech || word.word
      type = 2
    } else {
      audioKey = word.ukspeech || word.word
      type = 1
    }
    if (!audioKey) return
    // 设置播放中
    this.setData({ playingIndex: idx })
    const url = `https://dict.youdao.com/dictvoice?audio=${encodeURIComponent(audioKey)}&type=${type}`
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.src = url
    innerAudioContext.play()
    innerAudioContext.onEnded(() => {
      this.setData({ playingIndex: -1 })
      innerAudioContext.destroy()
    })
    innerAudioContext.onError(() => {
      this.setData({ playingIndex: -1 })
      innerAudioContext.destroy()
    })
  },

  onPhoneticModeSplit() {
    this.setData({ phoneticMode: 'split' })
  },
  onPhoneticModeNatural() {
    this.setData({ phoneticMode: 'natural' })
  },

  onPrevWord() {
    if (this.data.currentTab > 0) {
      const newIndex = this.data.currentTab - 1
      this.setData({
        currentTab: newIndex,
        currentModuleTab: 0  // 重置为学模块
      }, () => {
        this.updateCurrentWord(newIndex)
        this.scrollTabToCenter(newIndex)
      })
    } else {
      wx.showToast({
        title: '已经是第一个单词',
        icon: 'none'
      })
    }
  },

  onNextWord() {
    if (this.data.currentTab < this.data.wordList.length - 1) {
      const newIndex = this.data.currentTab + 1
      this.setData({
        currentTab: newIndex,
        currentModuleTab: 0  // 重置为学模块
      }, () => {
        this.updateCurrentWord(newIndex)
        this.scrollTabToCenter(newIndex)
      })
    } else {
      wx.showToast({
        title: '已经是最后一个单词',
        icon: 'none'
      })
    }
  },

  onModuleTabChange(e) {
    const idx = Number(e.currentTarget.dataset.index)
    this.setData({ currentModuleTab: idx })
    if (idx === 1) { // 拼模块
      this.initSpellGame(this.data.currentWord.word)
    } else if (idx === 2) { // 默模块
      this.setData({
        spellInput: [],
        spellStatus: ''
      })
    }
  },

  onModuleSwiperChange(e) {
    this.setData({ currentModuleTab: e.detail.current })
  },

  onTogglePronunciationMode() {
    const newMode = this.data.pronunciationMode === 'us' ? 'uk' : 'us';
    this.setData({
      pronunciationMode: newMode
    }, () => {
      this.updateCurrentWord(this.data.currentTab);
    });
  },

  highlightExampleEn(exampleEn, word) {
    if (!exampleEn || !word) return [{ text: exampleEn, highlight: false }]
    const reg = new RegExp(`(${word})`, 'ig')
    const parts = []
    let lastIndex = 0
    let match
    while ((match = reg.exec(exampleEn)) !== null) {
      if (match.index > lastIndex) {
        parts.push({ text: exampleEn.slice(lastIndex, match.index), highlight: false })
      }
      parts.push({ text: match[0], highlight: true })
      lastIndex = match.index + match[0].length
    }
    if (lastIndex < exampleEn.length) {
      parts.push({ text: exampleEn.slice(lastIndex), highlight: false })
    }
    return parts
  },

  scrollTabToCenter(idx) {
    wx.nextTick(() => {
      const query = wx.createSelectorQuery().in(this)
      query.select(`#tab-${idx}`).boundingClientRect()
      query.select('.custom-word-tabs').boundingClientRect()
      query.select('.custom-word-tab-list').boundingClientRect()
      query.exec(res => {
        if (!res[0] || !res[1] || !res[2]) return
        const tabRect = res[0]
        const scrollRect = res[1]
        const listRect = res[2]
        
        // 计算目标tab在列表中的相对位置
        const tabOffset = tabRect.left - listRect.left
        // 计算scroll-view的中心点
        const scrollCenter = scrollRect.width / 2
        // 计算需要滚动的距离，使tab居中
        const scrollLeft = tabOffset - scrollCenter + tabRect.width / 2
        
        this.setData({ 
          tabsScrollLeft: Math.max(0, scrollLeft)
        })
      })
    })
  },

  onReady() {
    this.setData({ tabsScrollLeft: 1000 })
  },

  // 进入拼模块时调用
  initSpellGame(word) {
    const parts1 = this.randomSplitWord(word, 2, 3)
    const parts2 = this.randomSplitWord(word, 1, 2)
    this.setData({
      spellStage: 1,
      spellParts1: this.shuffle(parts1),
      spellParts2: this.shuffle(parts2),
      spellUniqueParts1: this.shuffle(Array.from(new Set(parts1))),
      spellUniqueParts2: this.shuffle(Array.from(new Set(parts2))),
      spellInput: [],
      spellAnswer: parts1,
      spellStatus: ''
    })
  },

  // 随机分组
  randomSplitWord(word, minLen, maxLen) {
    let arr = []
    let i = 0
    while (i < word.length) {
      const remain = word.length - i
      const len = remain <= minLen ? remain : Math.min(maxLen, remain, Math.floor(Math.random() * (maxLen - minLen + 1)) + minLen)
      arr.push(word.slice(i, i + len))
      i += len
    }
    return arr
  },

  // 洗牌
  shuffle(arr) {
    return arr.slice().sort(() => Math.random() - 0.5)
  },

  // 用户点击词组
  onSpellSelect(e) {
    const item = e.currentTarget.dataset.item
    const stage = this.data.spellStage
    // 如果已被选过，不允许再次选择
    if (this.data.spellInput.includes(item)) return
    const input = this.data.spellInput.concat(item)
    this.setData({
      spellInput: input
    }, () => {
      if (input.length === this.data.spellAnswer.length) {
        const isRight = input.join('') === this.data.currentWord.word
        this.setData({ spellStatus: isRight ? 'success' : 'error' })
        if (isRight) {
          setTimeout(() => {
            if (stage === 1) {
              this.setData({
                spellStage: 2,
                spellInput: [],
                spellAnswer: this.data.spellParts2,
                spellStatus: ''
              })
            } else {
              this.setData({ currentModuleTab: 2 })
            }
          }, 800)
        } else {
          setTimeout(() => {
            this.setData({ spellInput: [], spellStatus: '' })
          }, 1000)
        }
      }
    })
  },

  // 拼写区发音支持美英音切换
  onSpellPronunciationMode(e) {
    const mode = this.data.pronunciationMode === 'us' ? 'uk' : 'us';
    this.setData({ pronunciationMode: mode }, () => {
      this.updateCurrentWord(this.data.currentTab);
    });
  },

  onSpellPlaySound() {
    const word = this.data.currentWord
    let audioKey = ''
    let type = 2
    if (this.data.pronunciationMode === 'us') {
      audioKey = word.usspeech || word.word
      type = 2
    } else {
      audioKey = word.ukspeech || word.word
      type = 1
    }
    if (!audioKey) return
    this.setData({ playingSpell: true })
    const url = `https://dict.youdao.com/dictvoice?audio=${encodeURIComponent(audioKey)}&type=${type}`
    const innerAudioContext = wx.createInnerAudioContext()
    innerAudioContext.src = url
    innerAudioContext.play()
    innerAudioContext.onEnded(() => {
      this.setData({ playingSpell: false })
      innerAudioContext.destroy()
    })
    innerAudioContext.onError(() => {
      this.setData({ playingSpell: false })
      innerAudioContext.destroy()
    })
  },

  // 拼写区重置
  onSpellReset() {
    this.setData({ spellInput: [], spellInputIdxs: [], spellStatus: '' })
  },

  onKeyboardTap(e) {
    const { key, type } = e.currentTarget.dataset;
    if (type === 'delete') {
      this.setData({
        spellInput: this.data.spellInput.slice(0, -1)
      });
    } else if (type === 'enter') {
      this.checkSpellAnswer();
    } else if (type === 'char') {
      if (this.data.spellInput.length < (this.data.currentWord.word ? this.data.currentWord.word.length : 30)) {
        this.setData({
          spellInput: this.data.spellInput.concat(key.toLowerCase())
        });
      }
    }
  },

  checkSpellAnswer() {
    const input = this.data.spellInput.join('')
    const isRight = input === this.data.currentWord.word
    this.setData({ spellStatus: isRight ? 'success' : 'error' })
    if (isRight) {
      setTimeout(() => {
        this.setData({ 
          currentModuleTab: 3,  // 切换到读模块
          spellInput: [],
          spellStatus: ''
        })
      }, 800)
    } else {
      setTimeout(() => {
        this.setData({ spellInput: [], spellStatus: '' })
      }, 1000)
    }
  },

  onShowKeyboard() {
    this.setData({ keyboardVisible: true });
  },
  onHideKeyboard() {
    this.setData({ keyboardVisible: false });
  },

  onNativeInput(e) {
    this.setData({
      spellInputStr: e.detail.value,
      spellInput: e.detail.value.split('')
    });
  },
  onNativeInputFocus() {
    this.setData({ inputFocus: true });
  },
  onNativeInputBlur() {
    this.setData({ inputFocus: false });
    // 失焦时校验
    this.checkNativeInput();
  },
  // 新增：回车时校验
  onNativeInputConfirm(e) {
    console.log('回车校验', e.detail.value);
    this.checkNativeInput();
  },
  checkNativeInput() {
    const input = this.data.spellInputStr.trim();
    const answer = this.data.currentWord.word || '';
    if (!input) {
      this.setData({ spellStatus: '' });
      return;
    }
    if (input.toLowerCase() === answer.toLowerCase()) {
      this.setData({ spellStatus: 'success' });
      setTimeout(() => {
        // 跳到下一个单词
        if (this.data.currentTab < this.data.wordList.length - 1) {
          const newIndex = this.data.currentTab + 1;
          this.setData({
            currentTab: newIndex,
            currentModuleTab: 0, // 重置为学模块
            spellInputStr: '',
            spellInput: [],
            spellStatus: '',
            inputFocus: true
          });
          this.updateCurrentWord(newIndex);
        } else {
          // 已是最后一个单词
          this.setData({
            spellInputStr: '',
            spellInput: [],
            spellStatus: '',
            inputFocus: false
          });
        }
      }, 1000);
    } else {
      this.setData({ spellStatus: 'error' });
      setTimeout(() => {
        this.setData({
          spellInputStr: '',
          spellInput: [],
          spellStatus: '',
          inputFocus: true
        });
      }, 1000);
    }
  },
}) 